package com.test.redis;

import com.test.utils.ApplicationContextUtil;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.Collection;
import java.util.Set;

/**
 * @author ssang
 * @date 2021-12-14 15:03
 */
public class RedisCache<K,V> implements Cache<K,V> {
    private String name ;

    public RedisCache(){

    }

    public RedisCache(String name){
        System.out.println("name="+name);
        this.name = name;
    }

    private RedisTemplate getRedisTemplate(){
        RedisTemplate redisTemplate = (RedisTemplate) ApplicationContextUtil.getBean("redisTemplate");
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        return redisTemplate;
    }

    @Override
    public V get(K k) throws CacheException {
        System.out.println("------------------get from "+k);
        System.out.println(k.getClass().toString());
        System.out.println(k.toString().getClass().toString());
        return (V) getRedisTemplate().opsForHash().get(name,k.toString());
    }

    @Override
    public V put(K k, V v) throws CacheException {
        System.out.println("------------------put "+ v +" with "+k);
        getRedisTemplate().opsForHash().put(name,k.toString(),v);
        return null;
    }

    @Override
    public V remove(K k) throws CacheException {
        System.out.println("------------------delete "+k);
        getRedisTemplate().opsForHash().delete(name,k.toString());
        return null;
    }

    @Override
    public void clear() throws CacheException {
        System.out.println("------------------clear");
        getRedisTemplate().opsForHash().delete(name);
    }

    @Override
    public int size() {
        return 0;
    }

    @Override
    public Set<K> keys() {
        return getRedisTemplate().opsForHash().keys(this.name);
    }

    @Override
    public Collection<V> values() {
        return getRedisTemplate().opsForHash().values(this.name);
    }
}
